<template>
  <div>
    <div>
      <el-tree
        ref="tree"
        v-loading="loading"
        :data="permissionList"
        default-expand-all
        :props="{label:'name'}"
        show-checkbox
        :check-strictly="true"
        node-key="id"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
// 导入树状结构数据
import { tranListToTreeData } from '@/utils/index'

import { editRoleId, assignPerm } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    childrenId: {
      type: [String || Number],
      required: true
    }
  },
  data() {
    return {
      permissionList: [], // 接收权限列表
      loading: false// 加载效果
    }
  },
  created() {
    // 调用权限列表数据方法
    this.getPermissionListFn()
    this.editRoleIdFn()// 回填已有角色方法
  },
  methods: {
    // 回填已有角色
    async editRoleIdFn() {
      const res = await editRoleId(this.childrenId)
      // console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
      // 树形控件树形点的选择中setCheckedKeys
    },

    // 获取权限列表
    async getPermissionListFn() {
      this.loading = true
      const res = await getPermissionList()
      // console.log(res)
      this.permissionList = tranListToTreeData(res.data)
      this.loading = false
    },
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },
    // 确定按钮
    async setRolesBtn() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({ id: this.childrenId, permIds })
      // console.log(res)
      this.$message.success(res.message)
      this.$emit('close')// 通知父组件关闭弹框
    }
  }

}
</script>

<style>

</style>
